package com.itdl.mq.base;


import com.itdl.mq.business.KeyExpireBusinessHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 默认Key过期监听 如果监听没有生效，请在Redis服务端添加或修改notify-keyspace-events Ex
 */
@ConditionalOnProperty(value = "redis.enable", havingValue = "true")
@Component
@Slf4j
@SuppressWarnings("all")
public class DefaultRedisKeyExpireListener extends KeyExpirationEventMessageListener {

    @Autowired(required = false)
    private List<KeyExpireBusinessHandle> keyExpireBusinessHandles;

    public DefaultRedisKeyExpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.info("=====>>>监听到key【{}】过期了", expiredKey);
        for (KeyExpireBusinessHandle handle : keyExpireBusinessHandles) {
            // 如果匹配到了key, 就执行对应的handle，如果有多个匹配，将会轮询处理
            if (handle.matchKey(expiredKey)){
                log.info("匹配到=====>>>【{}】处理过期key【{}】", handle.getClass().getName(), expiredKey);
                // 具体处理的方法
                try {
                    handle.handle(expiredKey);
                } catch (Exception e) {
                    log.error("=====>>>监听到key【{}】过期了, 但是处理器【{}】执行报错：{}" , expiredKey, handle.getClass().getName(), e.getMessage());
                    e.printStackTrace();
                }
            }
        }

    }
}
